﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Net.Mail;
using System.Data;
using System.Security.Cryptography;
using System.Text;

namespace Site.Secure
{
    public partial class Add_User : System.Web.UI.Page
    {

        /// <summary>
        /// Generates MD5 hash based on a string input.
        /// Please note this code comes directly from http://blogs.msdn.com/b/csharpfaq/archive/2006/10/09/how-do-i-calculate-a-md5-hash-from-a-string_3f00_.aspx
        /// </summary>
        /// <param name="input">String input of data to be hashed</param>
        /// <returns>128bit MD5 Hash of "input"</returns>
        public string CalculateMD5Hash(string input)
        {
            // step 1, calculate MD5 hash from input
            MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
            byte[] hash = md5.ComputeHash(inputBytes);

            // step 2, convert byte array to hex string
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
            {
                sb.Append(hash[i].ToString("x2"));
            }
            return sb.ToString();
        }

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (Session["userType"].ToString() == "admin" || Session["userType"].ToString() == "root") //If the current user is a admin allow them to continue
                {

                    if (edtUser.Text.Length != 0 && edtPass.Text != "" && edtEmail.Text != "") //Make sure the data is not null
                    {
                        string sPassHash = CalculateMD5Hash(edtPass.Text);
                        SqlDataSource1.InsertCommand = "INSERT INTO Users (User_Name, Password, Name, Surname, Email, User_Type, Cellphone) VALUES (@User_Name, @Password, @Name, @Surname, @Email, @User_Type, @Cellphone)";
                        SqlDataSource1.InsertParameters.Add("User_Name", edtUser.Text);
                        SqlDataSource1.InsertParameters.Add("Password", sPassHash);
                        SqlDataSource1.InsertParameters.Add("Name", edtName.Text);
                        SqlDataSource1.InsertParameters.Add("Surname", edtSurname.Text);
                        SqlDataSource1.InsertParameters.Add("Email", edtEmail.Text);
                        SqlDataSource1.InsertParameters.Add("User_Type", DropDownList1.Text);
                        SqlDataSource1.InsertParameters.Add("Cellphone", edtCellphone.Text);
                        SqlDataSource1.Insert();
                        //Logger.Log("The User '" + Session["userID"] + "' Created the user '" + edtUser.Text + "'", "USER CREATED", Server);
                         

                        //Send email to new user and send email to all existing users to inform about newly created account
                        
                        var smtp = new SmtpClient
                        {
                            Host = "africanhoneybee.net",
                            Port = 26,
                            EnableSsl = false,
                            DeliveryMethod = SmtpDeliveryMethod.Network,
                            UseDefaultCredentials = false,
                            Credentials = new NetworkCredential("noreply@africanhoneybee.net", "857105")
                        };

                        MailMessage message = new MailMessage();
                        message.From = new MailAddress("noreply@africanhoneybee.net", "AHB Webmaster");
                        message.To.Add(edtEmail.Text);
                        message.IsBodyHtml = true;
                        message.Subject = "AHB Account Registration";
                        message.Body = "<html><head><title>African Honey Bee Notification</title></head><body><h3>African Honey Bee Notification</h3><a> <p>A User account for Nektar has been created using this email address. You can now access the Nektar Managment page with the following login details:</p><p>Username: " + edtUser.Text + "</p><p>Password: " + edtPass.Text + "</p></a><p>Click <a href='http://www.africanhoneybee.net/Secure/'>here</a> to go to the Nektar login page</p></body></html>";
                        smtp.Send(message);

                        SqlDataSource1.SelectCommand = "SELECT * FROM Users";
                        DataView DV = (DataView)SqlDataSource1.Select(new DataSourceSelectArguments());                      

                        Response.Redirect("Default.aspx");
                    }
                    else
                        System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE='JavaScript'>alert('Please fill in all the required details')</SCRIPT>");
                }
                else
                {
                    System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE='JavaScript'>alert('You are not allowed to add users, please login with an account that has full root access')</SCRIPT>");
                }
            }
            catch(NullReferenceException ex)
            {
                //If you get here it means that Session == NULL, requires user to re-login
                System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE='JavaScript'>alert(Your session has expired, this means that you can not perform any root tasks on this website. Please login again or restart your browser and navigate back to this page.')</SCRIPT>");
            }
        }
    }
}